// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"fmt"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/library/hgorm/hook"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sSysWalletStoreBank struct{}

func NewSysWalletStoreBank() *sSysWalletStoreBank {
	return &sSysWalletStoreBank{}
}

func init() {
	service.RegisterSysWalletStoreBank(NewSysWalletStoreBank())
}

// Model 商家与银行卡ORM模型
func (s *sSysWalletStoreBank) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.WalletStoreBank.Ctx(ctx), option...)
}

// List 获取商家与银行卡列表
func (s *sSysWalletStoreBank) List(ctx context.Context, in *sysin.WalletStoreBankListInp) (list []*sysin.WalletStoreBankListModel, totalCount int, err error) {
	mod := s.Model(ctx, &handler.Option{FilterAuth: false})

	// 字段过滤
	mod = mod.FieldsPrefix(dao.WalletStoreBank.Table(), sysin.WalletStoreBankListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.WalletStoreBankListModel{}, &dao.Store, "store"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Store.Table(), dao.WalletStoreBank.Columns().StoreId, "=", dao.Store.Columns().Id)

	// 查询id
	if in.Id > 0 {
		mod = mod.Where(dao.WalletStoreBank.Columns().Id, in.Id)
	}

	// 查询银行卡号
	if in.AccountNum != "" {
		mod = mod.WhereLike(dao.WalletStoreBank.Columns().AccountNum, "%"+in.AccountNum+"%")
	}

	// 查询创建时间
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.WalletStoreBank.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 查询门店名称
	if in.StoreName != "" {
		mod = mod.WherePrefixLike(dao.Store.Table(), dao.Store.Columns().Name, "%"+in.StoreName+"%")
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.WalletStoreBank.Table() + "." + dao.WalletStoreBank.Columns().Id)

	// 操作人摘要信息
	mod = mod.Hook(hook.MemberSummary)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取商家与银行卡列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出商家与银行卡
func (s *sSysWalletStoreBank) Export(ctx context.Context, in *sysin.WalletStoreBankListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(sysin.WalletStoreBankExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出商家与银行卡-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []sysin.WalletStoreBankExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增商家与银行卡
func (s *sSysWalletStoreBank) Edit(ctx context.Context, in *sysin.WalletStoreBankEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		// 验证商户是否绑定银行卡
		if in.Id == 0 {
			flag, err := dao.WalletStoreBank.Ctx(ctx).Where(g.Map{
				dao.WalletStoreBank.Columns().StoreId: in.StoreId,
			}).Exist()
			if err != nil {
				err = gerror.Wrap(err, "获取商家信息失败，请稍后重试！")
				return err
			}
			if flag {
				err = gerror.New("当前商户已经绑定银行卡，请勿重复绑定")
				return err
			}
		}
		resp, err := wechat.GetBankInfo(ctx, in.AccountNum)
		if err != nil {
			err = gerror.New("获取银行卡信息失败，请稍后重试！")
			return
		} else if resp.Errcode != 0 {
			if resp.Errcode == 9710001 {
				err = gerror.New("请填写有效的银行卡号")
				return
			}
			err = gerror.New(resp.Errmsg)
			return
		}

		in.BankName = resp.Data[0].BankName
		// 修改
		if in.Id > 0 {
			in.UpdatedBy = contexts.GetUserId(ctx)
			if _, err = s.Model(ctx).
				Fields(sysin.WalletStoreBankUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.New("修改商家与银行卡失败，请稍后重试！")
			}
			return
		}

		// 新增
		in.CreatedBy = contexts.GetUserId(ctx)
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.WalletStoreBankInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.New("新增商家与银行卡失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除商家与银行卡
func (s *sSysWalletStoreBank) Delete(ctx context.Context, in *sysin.WalletStoreBankDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除商家与银行卡失败，请稍后重试！")
		return
	}
	return
}

// View 获取商家与银行卡指定信息
func (s *sSysWalletStoreBank) View(ctx context.Context, in *sysin.WalletStoreBankViewInp) (res *sysin.WalletStoreBankViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Hook(hook.MemberSummary).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取商家与银行卡信息，请稍后重试！")
		return
	}
	return
}

// 根据商户ID查询
func (s *sSysWalletStoreBank) GetByStoreId(ctx context.Context, storeId int64) (res *entity.WalletStoreBank, err error) {
	if err = s.Model(ctx).Where(dao.WalletStoreBank.Columns().StoreId, storeId).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取商家与银行卡信息，请稍后重试！")
		return
	}
	return
}

func (s *sSysWalletStoreBank) APIEditCard(ctx context.Context, in *sysin.WalletStoreBankAPIEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		resp, err := wechat.GetBankInfo(ctx, in.AccountNum)
		if err != nil {
			err = gerror.Wrap(err, "获取银行卡信息失败，请稍后重试！")
			return
		}
		backName := resp.Data[0].BankName
		if in.Code != consts.SmsSuperCode {
			if err = service.SysSmsLog().VerifyCode(ctx, &sysin.VerifyCodeInp{
				Event:  consts.SmsTemplateLogin,
				Mobile: in.Mobile,
				Code:   in.Code,
			}); err != nil {
				err = gerror.Wrap(err, "效验验证码失败，请稍后重试！")
				return
			}
		}
		// 商家权限检查
		{
			count, err := dao.StoreMember.Ctx(ctx).
				Where(dao.StoreMember.Columns().StoreId, in.StoreId).
				Where(dao.StoreMember.Columns().MemberId, contexts.GetUserId(ctx)).
				Where(dao.StoreMember.Columns().IsAdmin, 1).
				Count()
			if err != nil {
				err = gerror.Wrap(err, "获取商家信息失败，请稍后重试！")
				return err
			}
			if count == 0 {
				err = gerror.New("当前用户没有操作权限")
				return err
			}
		}

		// 绑定银行卡
		if in.ID == 0 {
			if err = s.Edit(ctx, &sysin.WalletStoreBankEditInp{
				WalletStoreBank: entity.WalletStoreBank{
					StoreId:     in.StoreId,
					AccountNum:  in.AccountNum,
					BankName:    backName,
					AccountName: in.AccountName,
					CreatedBy:   contexts.GetUserId(ctx),
					UpdatedBy:   contexts.GetUserId(ctx),
				},
			}); err != nil {
				err = gerror.Wrap(err, "新增商家与银行卡失败，请稍后重试！")
				return
			}
		}

		// 修改银行卡
		if in.ID > 0 {
			if _, err = s.Model(ctx).
				Fields(sysin.WalletStoreBankUpdateFields{}).
				WherePri(g.Map{
					dao.WalletStoreBank.Columns().Id: in.ID,
				}).Data(sysin.WalletStoreBankUpdateFields{
				AccountNum:  in.AccountNum,
				BankName:    backName,
				AccountName: in.AccountName,
				StoreId:     in.StoreId,
				UpdatedBy:   contexts.GetUserId(ctx),
			}).Update(); err != nil {
				err = gerror.Wrap(err, "修改商家与银行卡失败，请稍后重试！")
				return
			}
		}

		return
	})
}

// 提现
//func (s *sSysWalletStoreBank) Withdrawal(ctx context.Context, in *sysin.WalletStoreBankWithdrawalInp) (res *sysin.WalletStoreBankWithdrawalModel, err error) {
//	storeModel, err := service.SysStore().View(ctx, &sysin.StoreViewInp{Id: in.StoreID})
//	if err != nil {
//		err = gerror.Wrap(err, "获取商家失败")
//		return
//	}
//	if storeModel.Balance <= in.RequestAmount {
//		err = gerror.New("余额不足")
//		return
//	}
//
//	return
//}
